package hu.gar.core.dao.impl;

import hu.gar.core.dao.RoleDao;
import hu.gar.core.dao.UserDao;
import hu.gar.core.dao.UserToRoleDao;
import hu.gar.core.entity.Role;
import hu.gar.core.entity.UserToRole;
import hu.gar.vo.UserToRoleVO;

import java.util.List;

import javax.persistence.NoResultException;
import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class UserToRoleDaoImpl extends
		GenericDaoImpl<UserToRole, Long, UserToRoleVO> implements UserToRoleDao {

	
	private static final long serialVersionUID = -6011899280509950323L;

	@Autowired
	RoleDao roleDao;

	@Autowired
	UserDao userDao;

	@Override
	public List<Role> findByUserId(Long userId) {
		Query query = this.em
				.createQuery("SELECT r FROM  UserToRole  utr join utr.user u join utr.role  r  WHERE  u.id=:userId ");

		query.setParameter("userId", userId);
		List<Role> roles = query.getResultList();

		return roles;
	}

	@Override
	public UserToRole findByUserIdAndRoleId(Long userId, Long roleId) {
		try {
			Query query = this.em
					.createQuery("SELECT utr FROM  UserToRole  utr join utr.user u join utr.role  r  WHERE  u.id=:userId and r.id=:roleId");

			query.setParameter("userId", userId);
			query.setParameter("roleId", roleId);
			return (UserToRole) query.getSingleResult();

		} catch (NoResultException e) {
			return null;
		}
	}

	@Override
	public UserToRole toEntityImpl(UserToRole entity, UserToRoleVO vo) {
		entity.setRole(roleDao.toEntity(vo.getRole()));
		entity.setUser(userDao.toEntity(vo.getUser()));
		return entity;
	}

	@Override
	public UserToRoleVO toVOImpl(UserToRoleVO vo, UserToRole entity) {
		vo.setRole(roleDao.toVO(entity.getRole()));
		vo.setUser(userDao.toVO(entity.getUser()));
		return vo;
	}

	@Override
	public void addRoleToUser(Long userId, Long roleId) {

		UserToRole userToRole = new UserToRole(null, userDao.find(userId),
				roleDao.find(roleId));
		this.create(userToRole);
	}

	@Override
	public void removeRoleFromUser(Long userId, Long roleId) {
		UserToRole userToRole = findByUserIdAndRoleId(userId, roleId);
		this.delete(userToRole.getId());
	}

}
